package com.siwei.mes.service.laboratory.factory;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.siwei.mes.common.util.DateHelper;
import com.siwei.mes.common.util.UploadFlagUtils;
import com.siwei.mes.entity.experiment.Experiment;
import com.siwei.mes.entity.experiment.ExperimentDetail;
import com.siwei.mes.entity.laboratory.BaseData;
import com.siwei.mes.entity.laboratory.DataDefaultUc;
import com.siwei.mes.mapper.laboratory.DataDefUcLaboratoryMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * 上传协会通用方法
 *
 * @Description: 上传协会通用方法
 * @Version: 1.0
 * @author: mlchen
 * @date: 2025/3/28 22:18
 */
@Service
public class LaboratoryAbstractService {
    private static final Logger log = LoggerFactory.getLogger("laboratory");
    @Resource
    private DataDefUcLaboratoryMapper dataDefUcLaboratoryMapper;

    /**
     * 设置defuc值
     *
     * @param defaultUc     上海协会取样记录
     * @param experiment    试验委托信息
     * @param detectonPlace 检测地点
     * @param sampleNo      样本编号
     * @param jcrq          检测日期
     * @param detail        试验委托详情
     */
    public void setDefUc(DataDefaultUc defaultUc, Experiment experiment, String detectonPlace, String sampleNo, String jcrq, ExperimentDetail detail) {
        defaultUc.setSampleNo(sampleNo);
        defaultUc.setSampleName(experiment.getMaterialsName());
        //检测设备
/*        String equipment = "";
        if (detail.getEquipment() != null && !detail.getEquipment().isEmpty()) {
            for (String val : experiment.getEquipment().split(",")) {
                equipment += val + ";";
            }
        }*/
        defaultUc.setEquipment(detail.getEquipment());
        defaultUc.setTemperature(detail.getTemperature());
        defaultUc.setHumidity(detail.getHumidness());
        defaultUc.setDetectonRuleCode(detail.getExperimentGist());
        defaultUc.setAccessRuleCode(detail.getJudgeGist());
        defaultUc.setDetectonPlace(detectonPlace);

        Date date = null;
        if (StringUtils.isBlank(jcrq)) {
            //如果为空 则默认当前日期
            date = new Date();
        } else {
            date = DateHelper.parseDateTime(DateHelper.getDefaultDateFormat(), DateHelper.getDefaultLocal(), jcrq);
        }


        if (date == null) {
            log.error("检测日期转换错误。。。" + jcrq);
            throw new RuntimeException("检测日期转换错误。。。" + jcrq);
        }

        defaultUc.setDetectonDate(date);
        defaultUc.setDetectonMan(experiment.getSocietyUserName());
        defaultUc.setUploadFlag(UploadFlagUtils.CtoGB_Num(sampleNo, "z", defaultUc.getDetectonDate(), null));
        defaultUc.setDetectonManLoginType("0");
        defaultUc.setUCSampleRegular("1");
    }

    /**
     * 设置公共属性值
     *
     * @param sampleNo      样本编号
     * @param experiment    试验委托信息
     * @param baseData      上海协会公共实体
     * @param detectonPlace 检测地点
     * @param jcrq          检测日期
     * @param detail        试验委托详情
     */
    public void setCommonProperties(String sampleNo, Experiment experiment, BaseData baseData, String detectonPlace, String jcrq, ExperimentDetail detail) {
        baseData.setSampleNo(sampleNo);
        baseData.setSampleName(experiment.getMaterialsName());
        //检测设备
 /*       String equipment = "";
        if (detail.getEquipment() != null && !detail.getEquipment().isEmpty()) {
            for (String val : experiment.getEquipment().split(";")) {
                equipment += val + ";";
            }
        }*/
        baseData.setEquipment(detail.getEquipment());
        baseData.setTemperature(detail.getTemperature());
        baseData.setHumidity(detail.getHumidness());
        baseData.setDetectonRuleCode(detail.getExperimentGist());
        baseData.setAccessRuleCode(detail.getJudgeGist());
        baseData.setDetectonPlace(detectonPlace);

        Date date = null;
        if (StringUtils.isBlank(jcrq)) {
            date = new Date();
        } else {
            date = DateHelper.parseDateTime(DateHelper.getDefaultDateFormat(), DateHelper.getDefaultLocal(), jcrq);
        }
        if (date == null) {
            log.error("检测日期转换错误。。。" + jcrq);
            throw new RuntimeException("检测日期转换错误。。。" + jcrq);
        }
        baseData.setDetectonDate(date);
        baseData.setDetectonMan(experiment.getSocietyUserName());
        baseData.setUploadFlag(UploadFlagUtils.CtoGB_Num(sampleNo, "z", baseData.getDetectonDate(), null));
    }

    public void setUcStandardValue(DataDefaultUc defaultUc, String json, String value) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(json);
            if (rootNode != null) {
                JsonNode bbmjNode = rootNode.get(value);
                if (bbmjNode != null) {
                    boolean isNotContainMax = false;
                    boolean isNotContainMin = false;
                    String min = null;
                    String max = null;
                    if (bbmjNode.get("isNotContainMax") != null && "true".equals(bbmjNode.get("isNotContainMax").toString())) {
                        isNotContainMax = true;
                    }
                    if (bbmjNode.get("isNotContainMin") != null && "true".equals(bbmjNode.get("isNotContainMin").toString())) {
                        isNotContainMin = true;
                    }
                    if (bbmjNode.get("min") != null && StringUtils.isNotEmpty(bbmjNode.get("min").toString()) && !"null".equals(bbmjNode.get("min").toString())) {
                        min = bbmjNode.get("min").toString();
                    }
                    if (bbmjNode.get("max") != null && StringUtils.isNotEmpty(bbmjNode.get("max").toString()) && !"null".equals(bbmjNode.get("max").toString())) {
                        max = bbmjNode.get("max").toString();
                    }
                    String val = "";
                    if (min != null && max != null) {
                        if (isNotContainMin) {
                            val = val + ">" + min;
                        } else {
                            val = val + "≥" + min;
                        }

                        if (isNotContainMax) {
                            val = val + "<" + max;
                        } else {
                            val = val + "≤" + max;
                        }
                    } else if (min != null) {
                        if (isNotContainMin) {
                            val = val + ">" + min;
                        } else {
                            val = val + "≥" + min;
                        }
                    } else if (max != null) {
                        if (isNotContainMax) {
                            val = val + "<" + max;
                        } else {
                            val = val + "≤" + max;
                        }
                    }

                    if (!val.isEmpty()) {
                        log.info("取值json为：【{}】，standardValue值为：【{}】", json, val);
                        defaultUc.setUcStandardValue(val);
                    }
                }
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 查询data_defalutUc 是否存在 新增或修改
     *
     * @param sampleNo    样本编号
     * @param parameterID
     * @param defaultUc   上海协会取样记录
     */
    public void insertOrUpdateDataDefaultUc(String sampleNo, String parameterID, DataDefaultUc defaultUc) {
        //查询data_defalutUc 是否存在
        Map<String, Object> defaultUCBySampleNo = dataDefUcLaboratoryMapper.findDATA_DefaultUCBySampleNo(sampleNo, parameterID);
        if (defaultUCBySampleNo == null) {
            //新增
            dataDefUcLaboratoryMapper.addDATA_DefaultUC(defaultUc);
        } else {
            //修改
            dataDefUcLaboratoryMapper.updateDATA_DefaultUC(defaultUc);
        }

    }
}
